<template>
  <div class="main">
    <!-- 统计数据卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stats-item">
            <div class="stats-number">{{ stats.total }}</div>
            <div class="stats-label">设备总数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stats-item">
            <div class="stats-number">{{ stats.normal }}</div>
            <div class="stats-label">正常设备</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stats-item">
            <div class="stats-number">{{ stats.maintenance }}</div>
            <div class="stats-label">维护中</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stats-item">
            <div class="stats-number">{{ stats.repair }}</div>
            <div class="stats-label">维修中</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 工具栏 -->
    <el-card shadow="never" class="mb-4">
      <div class="flex items-center justify-between">
        <div class="flex items-center gap-4">
          <el-input
            v-model="searchForm.deviceName"
            placeholder="请输入设备名称"
            clearable
            style="width: 240px"
          />
          <el-input
            v-model="searchForm.deviceCode"
            placeholder="请输入设备编码"
            clearable
            style="width: 240px"
          />
          <el-select
            v-model="searchForm.deviceType"
            placeholder="设备类型"
            clearable
            style="width: 240px"
          >
            <el-option value="家电" label="家电" />
            <el-option value="家具" label="家具" />
            <el-option value="摄像头" label="摄像头" />
          </el-select>
          <el-button type="primary" @click="handleSearch"> 搜索 </el-button>
          <el-button @click="handleReset"> 重置 </el-button>
        </div>
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>
          新增设备
        </el-button>
      </div>
    </el-card>

    <!-- 设备列表表格 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="ID" width="80" align="center">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="deviceName"
          label="设备名称"
          width="120"
          align="center"
        />
        <el-table-column
          prop="deviceCode"
          label="设备编码"
          width="150"
          align="center"
        />
        <el-table-column
          prop="deviceType"
          label="设备类型"
          width="100"
          align="center"
        />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="success">正常</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="warning"
              >维护中</el-tag
            >
            <el-tag v-else type="danger">维修中</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="manufacturer"
          label="制造商"
          width="120"
          align="center"
        />
        <el-table-column
          prop="responsiblePerson"
          label="负责人"
          width="100"
          align="center"
        />
        <el-table-column
          prop="installDate"
          label="安装日期"
          width="160"
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.installDate">{{
              formatDate(scope.row.installDate)
            }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="installAddress"
          label="安装地址"
          align="center"
        />
        <el-table-column
          prop="maintenanceCount"
          label="维护次数"
          width="90"
          align="center"
        />
        <el-table-column
          prop="repairCount"
          label="维修次数"
          width="90"
          align="center"
        />
        <el-table-column label="操作" fixed="right" width="180" align="center">
          <template #default="scope">
            <el-button type="primary" text @click="handleView(scope.row)">
              查看
            </el-button>
            <el-button type="warning" text @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" text @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑设备对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="equipmentForm"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input
                v-model="equipmentForm.deviceName"
                placeholder="请输入设备名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备编码" prop="deviceCode">
              <el-input
                v-model="equipmentForm.deviceCode"
                placeholder="请输入设备编码"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select
                v-model="equipmentForm.deviceType"
                placeholder="请选择设备类型"
                style="width: 100%"
              >
                <el-option value="家电" label="家电" />
                <el-option value="家具" label="家具" />
                <el-option value="摄像头" label="摄像头" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备材质" prop="deviceMaterial">
              <el-input
                v-model="equipmentForm.deviceMaterial"
                placeholder="请输入设备材质"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备重量" prop="deviceWeight">
              <el-input
                v-model="equipmentForm.deviceWeight"
                placeholder="请输入设备重量"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number
                v-model="equipmentForm.price"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="equipmentForm.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备库存" prop="deviceStock">
              <el-input-number
                v-model="equipmentForm.deviceStock"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备状态" prop="status">
              <el-select
                v-model="equipmentForm.status"
                placeholder="请选择设备状态"
                style="width: 100%"
              >
                <el-option :value="0" label="正常" />
                <el-option :value="1" label="维护中" />
                <el-option :value="2" label="维修中" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安装日期" prop="installDate">
              <el-date-picker
                v-model="equipmentForm.installDate"
                type="datetime"
                placeholder="请选择安装日期"
                style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="安装地址" prop="installAddress">
              <el-input
                v-model="equipmentForm.installAddress"
                placeholder="请输入安装地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="responsiblePerson">
              <el-input
                v-model="equipmentForm.responsiblePerson"
                placeholder="请输入负责人"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="制造商" prop="manufacturer">
              <el-input
                v-model="equipmentForm.manufacturer"
                placeholder="请输入制造商"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制造商地址" prop="manufacturerAddress">
              <el-input
                v-model="equipmentForm.manufacturerAddress"
                placeholder="请输入制造商地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="制造商电话" prop="manufacturerPhone">
              <el-input
                v-model="equipmentForm.manufacturerPhone"
                placeholder="请输入制造商电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维护单位" prop="maintenanceUnit">
              <el-input
                v-model="equipmentForm.maintenanceUnit"
                placeholder="请输入维护单位"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="维护单位电话" prop="maintenanceUnitPhone">
              <el-input
                v-model="equipmentForm.maintenanceUnitPhone"
                placeholder="请输入维护单位电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维护单位地址" prop="maintenanceUnitAddress">
              <el-input
                v-model="equipmentForm.maintenanceUnitAddress"
                placeholder="请输入维护单位地址"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备维护人" prop="equipmentMaintainer">
              <el-input
                v-model="equipmentForm.equipmentMaintainer"
                placeholder="请输入设备维护人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登记日期" prop="registrationDate">
              <el-date-picker
                v-model="equipmentForm.registrationDate"
                type="datetime"
                placeholder="请选择登记日期"
                style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="equipmentForm.remarks"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="submitLoading"
            @click="handleSubmit"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看设备对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="查看设备信息"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备名称">{{
          viewEquipment.deviceName
        }}</el-descriptions-item>
        <el-descriptions-item label="设备编码">{{
          viewEquipment.deviceCode
        }}</el-descriptions-item>
        <el-descriptions-item label="设备类型">{{
          viewEquipment.deviceType
        }}</el-descriptions-item>
        <el-descriptions-item label="设备材质">{{
          viewEquipment.deviceMaterial
        }}</el-descriptions-item>
        <el-descriptions-item label="设备重量">{{
          viewEquipment.deviceWeight
        }}</el-descriptions-item>
        <el-descriptions-item label="价格">{{
          viewEquipment.price
        }}</el-descriptions-item>
        <el-descriptions-item label="单位">{{
          viewEquipment.unit
        }}</el-descriptions-item>
        <el-descriptions-item label="设备库存">{{
          viewEquipment.deviceStock
        }}</el-descriptions-item>
        <el-descriptions-item label="设备状态">
          <el-tag v-if="viewEquipment.status === 0" type="success">正常</el-tag>
          <el-tag v-else-if="viewEquipment.status === 1" type="warning"
            >维护中</el-tag
          >
          <el-tag v-else type="danger">维修中</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="安装日期">
          {{
            viewEquipment.installDate
              ? formatDate(viewEquipment.installDate)
              : "-"
          }}
        </el-descriptions-item>
        <el-descriptions-item label="安装地址">{{
          viewEquipment.installAddress
        }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{
          viewEquipment.responsiblePerson
        }}</el-descriptions-item>
        <el-descriptions-item label="制造商">{{
          viewEquipment.manufacturer
        }}</el-descriptions-item>
        <el-descriptions-item label="制造商地址">{{
          viewEquipment.manufacturerAddress
        }}</el-descriptions-item>
        <el-descriptions-item label="制造商电话">{{
          viewEquipment.manufacturerPhone
        }}</el-descriptions-item>
        <el-descriptions-item label="维护单位">{{
          viewEquipment.maintenanceUnit
        }}</el-descriptions-item>
        <el-descriptions-item label="维护单位电话">{{
          viewEquipment.maintenanceUnitPhone
        }}</el-descriptions-item>
        <el-descriptions-item label="维护单位地址">{{
          viewEquipment.maintenanceUnitAddress
        }}</el-descriptions-item>
        <el-descriptions-item label="设备维护人">{{
          viewEquipment.equipmentMaintainer
        }}</el-descriptions-item>
        <el-descriptions-item label="登记日期">
          {{
            viewEquipment.registrationDate
              ? formatDate(viewEquipment.registrationDate)
              : "-"
          }}
        </el-descriptions-item>
        <el-descriptions-item label="维护次数">{{
          viewEquipment.maintenanceCount || 0
        }}</el-descriptions-item>
        <el-descriptions-item label="维修次数">{{
          viewEquipment.repairCount || 0
        }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{
          viewEquipment.remarks
        }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import moment from "moment";
import type { Equipment, EquipmentQuery } from "@/api/equipment";
import {
  getEquipmentList,
  getEquipmentDetail,
  addEquipment,
  updateEquipment,
  deleteEquipment
} from "@/api/equipment";

// 定义组件名称
defineOptions({ name: "EquipmentInfo" });

// 状态管理
const loading = ref(false);
const dialogVisible = ref(false);
const viewDialogVisible = ref(false);
const dialogTitle = ref("新增设备");
const formRef = ref();
const submitLoading = ref(false);

// 统计数据
const stats = reactive({
  total: 0,
  normal: 0,
  maintenance: 0,
  repair: 0
});

// 搜索表单
const searchForm = reactive<EquipmentQuery>({
  page: 1,
  limit: 10,
  deviceName: "",
  deviceCode: "",
  deviceType: ""
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 表格数据
const tableData = ref<Equipment[]>([]);

// 表单数据
const equipmentForm = reactive<Equipment>({
  deviceName: "",
  deviceCode: "",
  deviceType: "",
  deviceMaterial: "",
  deviceWeight: "",
  price: 0,
  unit: "",
  deviceStock: 0,
  status: 0,
  installDate: "",
  installAddress: "",
  manufacturer: "",
  manufacturerAddress: "",
  manufacturerPhone: "",
  responsiblePerson: "",
  maintenanceUnit: "",
  maintenanceUnitPhone: "",
  maintenanceUnitAddress: "",
  equipmentMaintainer: "",
  registrationDate: "",
  remarks: ""
});

// 查看的设备数据
const viewEquipment = reactive<Equipment>({
  deviceName: "",
  deviceCode: "",
  deviceType: "",
  deviceMaterial: "",
  deviceWeight: "",
  price: 0,
  unit: "",
  deviceStock: 0,
  status: 0,
  installDate: "",
  installAddress: "",
  manufacturer: "",
  manufacturerAddress: "",
  manufacturerPhone: "",
  responsiblePerson: "",
  maintenanceUnit: "",
  maintenanceUnitPhone: "",
  maintenanceUnitAddress: "",
  equipmentMaintainer: "",
  registrationDate: "",
  remarks: ""
});

// 表单验证规则
const formRules = reactive({
  deviceName: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
  deviceCode: [{ required: true, message: "请输入设备编码", trigger: "blur" }],
  deviceType: [
    { required: true, message: "请选择设备类型", trigger: "change" }
  ],
  unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
  status: [{ required: true, message: "请选择设备状态", trigger: "change" }],
  installAddress: [
    { required: true, message: "请输入安装地址", trigger: "blur" }
  ],
  manufacturer: [{ required: true, message: "请输入制造商", trigger: "blur" }],
  responsiblePerson: [
    { required: true, message: "请输入负责人", trigger: "blur" }
  ]
});

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return "";
  return moment(date).format("YYYY-MM-DD HH:mm:ss");
};

// 生命周期
onMounted(() => {
  loadEquipmentList();
});

// 加载设备列表
const loadEquipmentList = async () => {
  loading.value = true;
  try {
    const params: EquipmentQuery = {
      ...searchForm,
      page: pagination.currentPage,
      limit: pagination.pageSize
    };
    const res = await getEquipmentList(params);
    if (res.code === 0 && res.data) {
      tableData.value = res.data.list || [];
      pagination.total = res.data.total || 0;

      // 更新统计数据
      stats.total = res.data.total || 0;
      stats.normal = tableData.value.filter(item => item.status === 0).length;
      stats.maintenance = tableData.value.filter(
        item => item.status === 1
      ).length;
      stats.repair = tableData.value.filter(item => item.status === 2).length;
    } else {
      ElMessage.error(res.message || "获取设备列表失败");
    }
  } catch (error) {
    console.error("获取设备列表失败:", error);
    ElMessage.error("获取设备列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  loadEquipmentList();
};

// 重置
const handleReset = () => {
  searchForm.deviceName = "";
  searchForm.deviceCode = "";
  searchForm.deviceType = "";
  handleSearch();
};

// 分页大小变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  loadEquipmentList();
};

// 当前页变化
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  loadEquipmentList();
};

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = "新增设备";
  dialogVisible.value = true;
  resetForm();
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(equipmentForm, {
    deviceName: "",
    deviceCode: "",
    deviceType: "",
    deviceMaterial: "",
    deviceWeight: "",
    price: 0,
    unit: "",
    deviceStock: 0,
    status: 0,
    installDate: "",
    installAddress: "",
    manufacturer: "",
    manufacturerAddress: "",
    manufacturerPhone: "",
    responsiblePerson: "",
    maintenanceUnit: "",
    maintenanceUnitPhone: "",
    maintenanceUnitAddress: "",
    equipmentMaintainer: "",
    registrationDate: "",
    remarks: ""
  });
};

// 查看设备
const handleView = async (row: Equipment) => {
  try {
    const response = await getEquipmentDetail(row.id!);
    if (response.code === 0 && response.data) {
      Object.assign(viewEquipment, response.data);
      viewDialogVisible.value = true;
    } else {
      ElMessage.error(response.message || "获取设备详情失败");
    }
  } catch (error) {
    console.error("获取设备详情异常:", error);
    ElMessage.error("获取设备详情失败");
  }
};

// 编辑设备
const handleEdit = async (row: Equipment) => {
  try {
    const response = await getEquipmentDetail(row.id!);
    if (response.code === 0 && response.data) {
      Object.assign(equipmentForm, response.data);
      dialogTitle.value = "编辑设备";
      dialogVisible.value = true;
    } else {
      ElMessage.error(response.message || "获取设备详情失败");
    }
  } catch (error) {
    console.error("获取设备详情异常:", error);
    ElMessage.error("获取设备详情失败");
  }
};

// 删除设备
const handleDelete = (id: number) => {
  ElMessageBox.confirm("确定要删除该设备吗？", "确认删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        const response = await deleteEquipment(id);
        if (response.code === 0) {
          ElMessage.success("删除成功");
          loadEquipmentList();
        } else {
          ElMessage.error(response.message || "删除失败");
        }
      } catch (error) {
        console.error("删除设备异常:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 取消删除
      ElMessage.info("删除已取消");
    });
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true;
      try {
        let response;
        if (dialogTitle.value === "新增设备") {
          response = await addEquipment(equipmentForm);
        } else {
          response = await updateEquipment(equipmentForm);
        }

        if (response.code === 0) {
          ElMessage.success(
            dialogTitle.value === "新增设备" ? "新增成功" : "更新成功"
          );
          dialogVisible.value = false;
          loadEquipmentList();
        } else {
          ElMessage.error(
            response.message ||
              (dialogTitle.value === "新增设备" ? "新增失败" : "更新失败")
          );
        }
      } catch (error) {
        console.error(
          dialogTitle.value === "新增设备" ? "新增设备异常:" : "更新设备异常:",
          error
        );
        ElMessage.error(
          dialogTitle.value === "新增设备" ? "新增失败" : "更新失败"
        );
      } finally {
        submitLoading.value = false;
      }
    }
  });
};
</script>

<style scoped>
.main {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 20px;
}

.stats-item {
  text-align: center;
}

.stats-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stats-label {
  color: #606266;
  font-size: 14px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.gap-4 {
  gap: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
